import { _decorator, Component, error, Material, MeshRenderer, Node, resources, v3, Vec3 } from 'cc';
import { EventManager, MyEvent } from './EventManager';
import { NUMBER } from './GameConstant';
import { ResourceUtil } from '../AshFramework/Utils/ResourceUtil';
import { Weapon } from './Weapon';
import { PrefsManager } from './PrefsManager';
const { ccclass, property } = _decorator;

@ccclass('ShowWeapon')
export class ShowWeapon extends Component {
    public static Instance: ShowWeapon = null;

    @property(Node)
    GunBody: Node = null;

    @property({ type: Weapon })
    WeaponTS: Weapon = null;

    MeshRenderer: MeshRenderer = null;
    NormalMaterial: Material = null;

    startEulerAngle: Vec3 = Vec3.ZERO;
    rotationSpeed = 10;
    isClick: boolean = false;
    angle: number = 0.5;


    protected onLoad(): void {
        ShowWeapon.Instance = this;
        this.MeshRenderer = this.GunBody.getComponent(MeshRenderer);
        this.NormalMaterial = this.MeshRenderer.getMaterial(0);
    }

    protected start(): void {
        this.show();
        this.changeSkin();
    }

    protected update(dt: number): void {
        if (this.isClick) return;
        this.node.eulerAngles = this.node.eulerAngles.add(v3(0, this.angle, 0));
    }

    show() {
        this.WeaponTS.showWeapon();
    }

    rotate(rotate: Vec3) {
        // 计算旋转角度
        const rotationY = rotate.x * this.rotationSpeed * 0.1;

        // 应用旋转
        this.node.eulerAngles = this.node.eulerAngles.add(v3(0, rotationY, 0));
    }

    changeSkin(number: NUMBER = PrefsManager.Instance.userData.checkedItem.PF) {
        let path = "";
        if (NUMBER.NUMBER1 == number) {
            this.MeshRenderer.material = this.NormalMaterial;
            return;
        } else {
            path = "WeaponMaterial" + number;
        }
        ResourceUtil.LoadMaterial(path).then((material: Material) => {
            this.MeshRenderer.material = material;
        })
    }

    protected onEnable(): void {
        EventManager.ON(MyEvent.SHOWROTATE, this.rotate, this);
    }
}


